package com.ropeok.dao.impl;

import com.ropeok.dao.PermissionDao;
import com.ropeok.entity.User;
import com.ropeok.entity.permissions;
import com.ropeok.util.c3p0Util;

import java.security.Permissions;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PermissionDaoImpl implements PermissionDao   {


     Connection connection=c3p0Util.getConnection();
//    Statement statement = connection.createStatement();



    @Override
    public List<permissions> FindAll()  {
        List<permissions> list=new ArrayList<>();
        try{
            PreparedStatement preparedStatement= connection.prepareStatement("select *from t_permissions");
            ResultSet resultSet = preparedStatement.executeQuery();
            permissions per;
            while (resultSet.next()){
                per=new permissions(); //实例化对象，避免创建的都是同一对象
                per.setPerid(resultSet.getInt("perid"));
                per.setName(resultSet.getString("name"));
                list.add(per);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void Save(permissions per) {

        try{
            PreparedStatement preparedStatement=connection.prepareStatement("insert into t_permissions values (?,?)");
            preparedStatement.setInt(1,per.getPerid());
            preparedStatement.setString(2,per.getName());
            preparedStatement.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }

    }

    @Override
    public void UpdatePermissions(Permissions per) {

    }

    @Override
    public void DelPermissions(int id) {
        try{
            PreparedStatement preparedStatement=connection.prepareStatement("delete from t_permissions where perid=?");
            preparedStatement.setInt(1,id);
            preparedStatement.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    @Override
    public List<permissions> findByRoleId(Integer id) {
        List<permissions> list = new ArrayList<>();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("select perid,name from t_permissions tp,role_permission rp where tp.perid =rp.permisssion_id and rp.role_id=? ;");
            preparedStatement.setInt(1,id);
            ResultSet resultSet = preparedStatement.executeQuery();
            permissions per;
            while (resultSet.next()) {
                per = new permissions(); //实例化对象，避免创建的都是同一对象
                per.setPerid(resultSet.getInt("perid"));
                per.setName(resultSet.getString("name"));
                list.add(per);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
